package cn.hchaojie.ssm.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.hchaojie.ssm.domain.AjaxResponse;
import cn.hchaojie.ssm.domain.Category;
import cn.hchaojie.ssm.domain.Post;
import cn.hchaojie.ssm.service.CategoryService;
import cn.hchaojie.ssm.service.PostService;

/**
 * web层：请求参数封装、请求路径映射
 * spring mvc (model, view, controller)
 */
@Controller
//@RequestMapping("/blog/post")
public class PostController {
	@Autowired
	PostService service;
	
	@Autowired
	CategoryService categoryService;

	// http://localhost/springmvc/pages/list.action
	@RequestMapping("/pages/list")
	public ModelAndView list(Model model, HttpServletRequest request) {

		// 查询所有文章列表
		List<Post> posts = service.findAll();
		
		// 查询所有分类，初始化分类的下拉列表
		List<Category> categories = categoryService.findAll();
		
		// 跳转到文章列表对应的jsp页面，并且把文章列表显示出来
		ModelAndView mv = new ModelAndView();	// 跳到哪个页面（view），页面上需要显示什么数据（model）
		mv.setViewName("posts");
		// mv.addObject("posts", posts);		// posts对象会传给jsp页面
		model.addAttribute("posts", posts);
		model.addAttribute("categories", categories);
		
		return mv;
	}
	
	@RequestMapping("/post/findPage")
	public String findPage(
			@RequestParam(name = "page", defaultValue = "1") Integer page, 
			@RequestParam(name = "size", defaultValue = "10") Integer size,
			Model model) {
		
		AjaxResponse<Post> pageData = service.searchPage(null, null, null, page, size);
		
		// 算一共多少页
		int totalPage = (pageData.getCount() - 1) / size + 1;
		
		model.addAttribute("posts", pageData.getData());
		model.addAttribute("currentPage", page);
		model.addAttribute("totalPage", totalPage);
		
		return "posts";
	}
	
	@RequestMapping("/pages/list_json")
	@ResponseBody
	public List<Post> listJson() {
		// 查询所有文章列表
		List<Post> posts = findPosts();
		
		return posts;
	}
	
	@RequestMapping("/pages/post_by_id")
	@ResponseBody	// 对返回数据进行序列化
	public Post findById(int id) {
		Post p = new Post();
		p.setId(id);
		p.setTitle("java");
		p.setCreated(new Date());
		
		Category c = new Category();
		c.setId(2);
		c.setName("spring");
		
		p.setCategory(c);
		
		return p;
	}
	
	private List<Post> findPosts() {
		List<Post> posts = new ArrayList<>();
		
		for (int i = 0; i < 10; i++) {
			Post p = new Post();
			p.setId(i + 1);
			p.setTitle("java spring mvc" + i);
			p.setCreated(new Date());
			
			posts.add(p);
		}
		
		return posts;
	}
	
	@RequestMapping("/post/edit_form")
	public String eidtForm(@RequestParam("id") int id, Model model) {
		// 根据id查询文章信息
		Post post = service.getByIdWithCategory(id);
		
		// 查询所有分类
		List<Category> categories = categoryService.findAll();

		model.addAttribute("post", post);
		model.addAttribute("categories", categories);
		
		return "post_form";
	}
	
	@RequestMapping("/post/edit")
	public String edit(Post p, Model model, @RequestParam("uploadFile") MultipartFile file) {
		service.update(p.getId(), p);
		
		// 文件名字：
		String fileName = file.getOriginalFilename();
		System.out.println("上传的文件名：" + fileName);
		System.out.println("文件大小：" + file.getSize());
		
		if (fileName != null && fileName.length() != 0) {
			// 文件复制到磁盘某个路径
			try {
				file.transferTo(new File("C:\\Users\\hchaojie\\" + fileName));
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
		
		return "redirect:/pages/list.action";
	}
	
	@RequestMapping("/post/insert")
	public String insert(Post p) {
		service.insert(p);
		return "success";
	}
	
	@RequestMapping("/post/delete")
	public String delete(@RequestParam("id") int id, Model model) {
		service.deleteById(id);
		
//		List<Post> posts = service.findAll();
//		model.addAttribute("posts", posts);
		
		return "redirect:/pages/list";
	}
	
//	/**
//	 * 批量删除
//	 * @return
//	 */
//	@ResponseBody
//	@RequestMapping("/post/deleteBatch")
//	public Map<String, Object> deleteBatch(@RequestParam("ids") String[] ids) {
//		service.deleteBatch(ids);
//		
//		//{"success":true, "message":"删除成功！"}
//		Map<String, Object> result = new HashMap<>();
//		result.put("success", true);
//		result.put("message", "删除成功!");
//		
//		return result;
//	}
	
	/**
	 * 批量删除
	 * @return
	 */
	@RequestMapping("/post/deleteBatch")
	public String deleteBatch(@RequestParam("ids") String[] ids) {
		service.deleteBatch(ids);
		
		return "redirect:/pages/list";
	}
	
	@RequestMapping("/post/search")
	public String search(
			@RequestParam(name = "page", defaultValue = "1") Integer page, 
			@RequestParam(name = "size", defaultValue = "10") Integer size,
			Post p, Model model) {
		// 把查询参数回显到表单
		if (!StringUtils.isEmpty(p.getTitle())) {
			model.addAttribute("title", p.getTitle());
		}
		
		if (p.getCreated() != null) {
			model.addAttribute("created", p.getCreated());
		}
		
		if (p.getCategory() != null && p.getCategory().getId() != null) {
			model.addAttribute("cid", p.getCategory().getId());
		}
		
		Integer cid = p.getCategory() == null ? null : p.getCategory().getId();
		AjaxResponse<Post> pageData = service.searchPage(p.getTitle(), cid, p.getCreated(), page, size);
		
		// 查询所有分类，初始化分类的下拉列表
		List<Category> categories = categoryService.findAll();
		
		// 算一共多少页
		int totalPage = (pageData.getCount() - 1) / size + 1;
		
		model.addAttribute("posts", pageData.getData());
		model.addAttribute("currentPage", page);
		model.addAttribute("totalPage", totalPage);
		
		model.addAttribute("categories", categories);


		return "posts";
	}
}
